const http = require('http');
const chatsService = require('./services/chats.service');

class ConnectWebSocket {
  constructor({app}) {
    const server = http.createServer(app);
    const io = require('socket.io')({
      path: '/v1/ws/chat2',
      serverClient: false,
      pingInterval: 10000,
      pingTimeout: 5000,
      cookie: false
    })
    io.attach(server);
    this.io = io;
    this.server = server;
    this.connectMap = {};
  }

  connect = ({PORT}) => {
    this.io.on('connection', socket => {
      let id = socket.id;
      this.connectMap[id] = null;

      socket.on('recordId', data => {
        this.connectMap[data.userId] = socket.id;
      });

      socket.on('sendMessage', async inputData => {
        inputData = JSON.parse(inputData);
        const {receiveId} = inputData;
        let receiveSocketId = this.connectMap[receiveId];
        // 有，说明在线
        if (receiveSocketId) {
          const {data} = await chatsService.saveChatContentService(inputData);
          socket.to(receiveSocketId).emit('receiveMessage', data);
        }
        // 没有，说明不在线
        else {
          console.log(`${receiveId} 用户不在线`);
        }
      });
      socket.on('disconnect', () => {
        for (let key in this.connectMap) {
          if (this.connectMap[key] === socket.id) {
            delete this.connectMap[key];
          }
        }
      });
    });

    this.server.listen(PORT, err => {
      if (err) {
        console.log(err);
      } else {
        console.log(`server is running at http://localhost:${PORT}`);
      }
    });

  };
}

module.exports = ConnectWebSocket;

